package com.gcsj.gcsjspringboot.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gcsj.gcsjspringboot.common.utils.Constant;
import com.gcsj.gcsjspringboot.common.utils.R;
import com.gcsj.gcsjspringboot.entity.DeptPage;
import com.gcsj.gcsjspringboot.entity.SysDeptEntity;
import com.gcsj.gcsjspringboot.entity.SysUserEntity;
import com.gcsj.gcsjspringboot.service.SysDeptService;
import com.gcsj.gcsjspringboot.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.print.Book;
import java.util.HashMap;
import java.util.List;


/**
 * 部门管理
 *
 * @author
 */

@RestController
@RequestMapping("/dept")
public class SysDeptController extends AbstractController {
    @Autowired
    private SysDeptService sysDeptService;

    @PostMapping("/list")
    public R getPage(@RequestBody DeptPage deptPage) {
//        System.out.println(deptPage);
        IPage<SysDeptEntity> page = sysDeptService.getPage(deptPage);
        //如果当前页码值大于了总页码值，那么重新执行查询操作
        if(deptPage.getCurrentPage() > page.getPages()){
            deptPage.setCurrentPage((int)page.getPages());
            page = sysDeptService.getPage(deptPage);
        }
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("list", page);
        return R.ok(hashMap);
    }

    @GetMapping("/selectById")
    public R selectById(@RequestParam int deptId) {//编辑前先根据id查找并返回这一条数据
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("list", sysDeptService.getById(deptId));
        return R.ok(hashMap);
    }

    @GetMapping("/basicDepts")
    public R basicDepts() {
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("list", sysDeptService.getBasicDepts());
        return R.ok(hashMap);
    }

    @PostMapping("/save")
    public R deptSave(@RequestBody SysDeptEntity sysDeptEntity) {
//        System.out.println(sysDeptEntity);
        if(sysDeptEntity.getDeptId() == null) {//没有id说明是添加
            sysDeptService.save(sysDeptEntity);
        }else {//有id说明是更新
            sysDeptService.updateById(sysDeptEntity);
        }
        return R.ok("保存成功!");
    }

//删除先判断是否有子部门，若有则不能删除
    @GetMapping("/delete")
    public R delete(@RequestParam Integer deptId){
        if(sysDeptService.subDeptID(deptId)==0){//删除前先判断是否有子部门，若没有则能删除
            sysDeptService.removeById(deptId);
            return R.ok("删除成功!");
        }
        return R.error("该部门存在子部门，无法删除!");
    }

}
